﻿param(
    [Parameter(Mandatory=$true)]
    [string] $SimulateTimes = 5
  )

push-location
$curpwd = split-path -parent $myinvocation.mycommand.definition
set-location $curpwd

. .\config.ps1
  
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100


$SIMULATE_VISIT_TIMES=$SimulateTimes
$DictEmployee = @{}
$TRY_TIMES = 5
 
Function GetRandomUserByDept($dept)
{
    $dept_code = $dept
    write-host $dept_code
    if( $DictEmployee.Keys -notcontains $dept_code){
        $query_dept = "select code,name,dept_sn from a_employee_mi(nolock) where prof_type in ('01', '03') and dept_sn='{0}'" -f $dept_code
        $DictEmployee[$dept_code] = Invoke-Sqlcmd -ServerInstance $SQLSERVER -Database $DB -Query $query_dept -Username "sa" -Password "system"
    }
    $empRamdomIdx = Get-Random -Minimum 0 -Maximum  ([System.Int32]$DictEmployee[$dept_code].Length-1)     
    return $DictEmployee[$dept_code][$empRamdomIdx]
}
  

$Query = "select patient_id,name,ward from zy_actpatient(nolock)"
$patientList = Invoke-Sqlcmd -ServerInstance $SQLSERVER -Database $DB -Query $Query -Username $USERNAME -Password $PASSWORD


foreach($i in (1..$SIMULATE_VISIT_TIMES))
{ 
$ie = new-object -com InternetExplorer.Application
$ie.visible=$true
    Write-Host("模拟访问次数：{0}" -f $i)
    $patientRamdomIdx = Get-Random -Minimum 0 -Maximum  ([System.Int32]$patientList.Length-1)   
    $pat = $patientList[$patientRamdomIdx]
   # foreach($pat in $patientList){
        $patient_id = $pat["patient_id"]
        write-host $pat["patient_id"],$pat["name"]
                
        $user = GetRandomUserByDept($pat["ward"])
        Write-Host ("根据科室编码随机获取本科内的用户:{0} {1}" -f   $user["code"],$user["name"])
        $patient_visit_type = "02"
        $url = "http://192.168.0.191:8001/cdr/login/loginInpatientIntegrated.html?userId={2}&patientId={0}&domainId={1}&inpatientType=02&sceneType=11" -f $patient_id, $patient_visit_type,$user["code"]
        
        Write-Host ("修改URL地址:{0}" -f $url)
        $ie.navigate("$url")
        Write-Host ("修改URL地址成功")
        $try_i = 1
#        while($ie.ReadyState -ne 4) {
#            if($try_i > $TRY_TIMES){
#                Write-Host("状态没准备好")
#                break
#            }
#            start-sleep -m 100
#            $try_i = $try_i + 1        
 #       }
        $random_sleep = Get-Random -Minimum 1000 -Maximum  5000
        Write-Host ("启动随机休眠：{0}ms" -f $random_sleep)
        start-sleep -m $random_sleep
   # }
$ie.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)
Remove-Variable ie
 }



